package com.dbdata.move.service;

import com.dbdata.move.Utils;
import com.dbdata.move.dao.TeacherDao;
import com.dbdata.move.model.*;
import com.wksc.commons.utils.date.DateUtils;
import com.wksc.commons.utils.string.StringUtils;
import opensource.jpinyin.PinyinFormat;
import opensource.jpinyin.PinyinHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Richard
 */
@Service
public class TeacherService {

    private static final Logger L = LoggerFactory.getLogger(TeacherService.class);

    @Autowired
    private TeacherDao dao;

    /**
     * 保存教员信息
     */
    public void saveTeacher() {
        String filePath = "D:\\VMShare\\\\Ins.txt";
        String dataFormat = "yyyy/MM/dd HH:mm:ss";

        List<String> list = new ArrayList<String>();
        try {
            list = Utils.readCsvFileNoHead(filePath, "UTF-8");
        } catch (IOException e) {
            L.error("读取教员原始数据文件出错！", e);
        }

        String[] columns;
        try {
            for (String s : list) {
                columns = s.split(",");
                L.debug("========开始保存用户：{}==========", columns[1]);
                UserBaseInfo userBaseInfo = new UserBaseInfo();
                // 设置用户类型为“教员”
                userBaseInfo.setUserType((byte) 1);
                // 教员
                Teacher teacher = new Teacher();
                // 组织机构
                Organize organize = new Organize();
                // 行政职务
                AdministrativeJob job = new AdministrativeJob();

                // 教员姓名
                userBaseInfo.setUserName(columns[1]);
                // 身份证
                String identityCard = StringUtils.defaultString(columns[2]).trim().toUpperCase();
                userBaseInfo.setIdentityCard(columns[2]);
                if (StringUtils.isNotBlank(identityCard)) {
                    boolean sex = Integer.parseInt(identityCard.substring(identityCard.length() - 2, identityCard.length() -
                                                                                                     1)) % 2 == 1;
                    userBaseInfo.setSex(sex);
                }

                userBaseInfo.setAccountState((byte) 1);
                // 姓名拼音
                userBaseInfo.setSpell(PinyinHelper.convertToPinyinString(
                        columns[1], " ", PinyinFormat.WITHOUT_TONE
                ));

                // 拼音缩写
                userBaseInfo.setPinYinSx(columns[5]);

                if (null != columns[9] && !columns[9].equals("")) {
                    // 体检合格日期
                    teacher.setQualifiedDate(DateUtils.stringToDate(columns[9],
                            dataFormat));
                }

                // 组织机构id
                organize.setId(Utils.getOrganizeId(columns[11]));
                userBaseInfo.setOrganize(organize);

                //指挥员
                boolean commander = Boolean.parseBoolean(columns[13].toLowerCase());
                teacher.setCommander(commander);
                //平均小时补贴
                teacher.setHourSubsidy(Integer.parseInt(columns[14]) * 0.01f);
                //岗位倾斜系数
                teacher.setInclineSubsidy(Integer.parseInt(columns[15]) * 0.01f);
                //飞行奖章
                teacher.setFlightMedal(Integer.parseInt(columns[16])*1f);
                if (null != columns[22] && !columns[22].equals("")) {
                    userBaseInfo.setCreateDate(DateUtils.stringToDate(columns[22],
                            dataFormat));
                }

                job.setId(getJobId(columns[26]));
                teacher.setAdministrativeJob(job);

                // 列索引,30:邮箱, 31:全英语教学, 32:MPL教师, 33:可带飞新教师
                boolean englishOnly = Boolean.parseBoolean(columns[31].toLowerCase());
                teacher.setEnglishOnly(englishOnly);
                boolean mplTeacher = Boolean.parseBoolean(columns[32].toLowerCase());
                teacher.setMplTeacher(mplTeacher);
                boolean teacherTeacher = Boolean.parseBoolean(columns[33].toLowerCase());
                teacher.setTeacherTeacher(teacherTeacher);
                //性别默认教员为男
                userBaseInfo.setSex(true);
                teacher.setUserBaseInfo(userBaseInfo);

                // 在职
                teacher.setIncumbent(Byte.parseByte(columns[17]));


                TeacherTitle teacherTitiles = new TeacherTitle();
                if (null != columns[7] && !columns[7].equals("")) {
                    teacherTitiles.setDate(DateUtils.stringToDate(columns[7],
                            dataFormat));
                }

                Set<TeacherTitle> set = new HashSet<TeacherTitle>(1);
                set.add(teacherTitiles);
                teacher.setTeacherTitles(set);
                dao.save(teacher);


                TeacherTitleId teacherTitilesId = new TeacherTitleId();
                teacherTitilesId.setTeacherId(teacher.getId());
                teacherTitilesId.setTitleId(getTechnicalTitilesId(columns[6]));

                teacherTitiles.setId(teacherTitilesId);
                dao.save(teacherTitiles);

                L.debug("========保存用户：{}=成功=========", columns[1]);

//                L.debug("教员姓名：{}，拼音：{}", columns[1], PinyinHelper
//                        .convertToPinyinString(columns[1], " ", PinyinFormat.WITHOUT_TONE));
            }
        } catch (ParseException e) {
            L.error("日期转换失败！", e);
        }

    }

    /**
     * 获取原系统职称id对应新系统职称id的值
     * @param oldTechnicalTitilesId 原系统职称id
     * @return 新系统职称id
     */
    private Long getTechnicalTitilesId(String oldTechnicalTitilesId) {
        // 获取职称 0:特级，1:一级，2:二级，3:三级，4:见习
        // 与新系统对应关系:0->1,1->2,2->3,3->4,4->5
        if (!"".equals(oldTechnicalTitilesId)) {
            switch (Integer.parseInt(oldTechnicalTitilesId)) {
                case 0:
                    return 1L;
                case 1:
                    return  2L;
                case 2:
                    return 3L;
                case 3:
                    return 4L;
                case 4:
                    return 5L;
                default:
                    return 5L;
            }
        }
        // 默认为“见习”
        return 5L;
    }

    /**
     * 获取原系统职务id对应新系统职务id的值
     * @param jobId 原系统职务id
     * @return 新系统职务id
     */
    private Long getJobId(String jobId) {
        // 原系统 职务 0:无职务,5:副科级, 10:副科长, 15:科级, 20:科长, 25:副处级, 30:副处长, 35:处级
        // 40:处长, 45:副司局级, 50:副司局长, 55:司局级, 60:司局长
        if (!"".equals(jobId)) {
            switch (Integer.parseInt(jobId)) {
                case 0:
                    return 1L;
                case 5:
                    return 2L;
                case 10:
                    return 3L;
                case 15:
                    return 4L;
                case 20:
                    return 5L;
                case 25:
                    return 6L;
                case 30:
                    return 7L;
                case 35:
                    return 8L;
                case 40:
                    return 9L;
                case 45:
                    return 10L;
                case 50:
                    return 11L;
                case 55:
                    return 12L;
                case 60:
                    return 13L;
                default:
                    return 1L;
            }
        }
        return 1L;
    }

}
